<template>
  <div class="home">
      <h2>测试 WebSocket</h2>
      <button @click="stop">停止推送</button>
      <button @click="start">继续推送</button>
      <button @click="close">断开连接</button>
      <button @click="clear">清空</button>
      <div class="box">
        <p v-for="(item,index) in resData" :key="index" :class="{'ping' : item==='服务器已收到数据:【ping】'}">
            {{item}}
        </p>
      </div>
  </div>
</template>

<script>
    import WebSocketClient from "../util/webSocketClient"

    export default {
        name: 'HomeView',
        data(){
            return {
                client : null,
                resData : []
            }
        },
        created(){
            this.wsClient = new WebSocketClient("ws://192.168.5.148:3000/wbs/echo");
            // 设置回调函数
            this.wsClient.onOpen = () => {
                console.log('ws1 connected...');
            };
            this.wsClient.onError = (error) => {
                console.error('ws1 error:', error);
            };
            this.wsClient.onMessage = (event) => {
                // console.log('ws1 received message:', event.data);
                this.resData.push(event.data)
            };
        },
        beforeDestroy(){
            this.wsClient.disconnect(); // 组件销毁前断开与服务端WebSocket的连接
        },
        methods : {
            stop(){
                this.wsClient.send('end');
            },
            start(){
                this.wsClient.send('start');
            },
            close(){
                this.wsClient.disconnect();
                this.wsClient = null;
            },
            clear(){
                this.$refs.box.innerHTML = ''
            }
        },
     }
</script>
<style>
    .box {
        width: 600px;
        height: 400px;
        background: #333;
        color: #fff;
        overflow-y: auto;
        margin:  50px auto;
    }
    .ping {
        color : yellow;
    }
</style>
